/*
 * @Author: myw
 * @Email: 516378746@qq.com
 * @Date: 2020-03-02 17:03:49
 * @Descripttion: 移库入库
 */
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, Validators, AbstractControl, Form, FormControl } from '@angular/forms';
import { MovewareApplyService } from './moveware-apply.service';
import { DatePipe } from '@angular/common';
import { NzModalService, NzMessageService } from 'ng-zorro-antd';

@Component({
    selector: 'app-moveware-apply',
    templateUrl: './moveware-apply.component.html',
    styleUrls: ['./moveware-apply.component.scss']
})
export class MovewareApplyComponent implements OnInit {

    selectedValue = null;
    listData = [];
    dataCount: number = 0;
    pageIndex: number = 1;
    pagesize: number = 10;
    isShow: boolean = false;
    applyForm: FormGroup;
    sourceHouseData = [];       // 搜索条件库房列表
    subMaterialList = [];
    materiHouseData = [];       // 弹框中库房列表
    sourceAreaData = [];
    targetAreaData = [];
    batchData = [];
    sourceWareHouseSearch: any = '';
    selectedMaterialItem: { [id: string]: any } = {}
    rangeDate = [];
    moveWareTypeList = [];
    chooseWareTypeList = [];
    sourceHouseId: null;
    targetHouseId: null;
    chooseTypeValue: number = -1;
    modalList = [];
    deleteIds = [];
    checkedArr: { [key: number]: boolean } = {}
    isAllChecked: boolean = false;
    isHalfChecked: boolean = false;
    editId: number = -1;

    modalDomBox : any

    constructor(
        private fb: FormBuilder,
        private datePipe: DatePipe,
        private modal: NzModalService,
        private nzmessage: NzMessageService,
        private applyService: MovewareApplyService
    ) { }

    ngOnInit() {
        this.modalDomBox = document.querySelector("#modal_box");
        this.applyForm = this.fb.group({
            materialCode: [null, Validators.required],
            materialName: [null],
            batch: [null, Validators.required],
            batchNum: [null, Validators.required],
            sourceHouse: [null, [Validators.required, this.isSameHouseValidator()]],
            sourceArea: [null, [Validators.required, this.isSameAreaValidator(1)]],
            targetHouse: [null, [Validators.required, this.isSameHouseValidator()]],
            targetArea: [null, [Validators.required, this.isSameAreaValidator(2)]],
            moveNum: [null, [Validators.required, this.moveNum()]],
            moveType: [null, Validators.required],
            chooseType: [null, Validators.required]
        })
        this.getList();
        this.getSourceHouseList();
        this.getSubMaterialList();
        this.getMoveWareType();
        this.getChooseWareType();
    }

    isSameAreaValidator(type) {
        return (control: FormControl) => {
            if (control.value) {
                let _value = type == 1 ? this.applyForm.controls.targetArea.value : this.applyForm.controls.sourceArea.value;
                if (control.value == _value) {
                    return { "sameArea": true }
                }
            }
            return null
        }
    }
    isSameHouseValidator() {
        return (control: FormControl) => {
            if (control.value) {
                let _controls = this.applyForm.controls
                if (_controls.moveType.value == 4 && (_controls.sourceHouse.value != _controls.targetHouse.value)) {
                    return { "noSameHouse": true }
                }
            }
            return null
        }
    }
    moveNum() {
        return (control: AbstractControl) => {
            if (control.value) {
                if (control.value > this.applyForm.controls.batchNum.value) {
                    return { "moveNum": true }
                }
            }
            return null
        }
    }

    showModal(data?) {
        this.isShow = true;
        if (data) {
            this.editId = data.id;
            console.log(data);
            this.applyForm.patchValue({
                materialCode: data.materialCode,
                materialName: data.materialName,
                batch: data.barcodeBatch,
                batchNum: data.barcodeBatchWeight,
                sourceHouse: data.fromStorehouse.id,
                sourceArea: data.fromStorehouseArea.id,
                targetHouse: data.toStorehouse.id,
                targetArea: data.toStorehouseArea.id,
                moveNum: data.reqAmount,
                moveType: "" + data.movementType,
                chooseType: data.pickingType
            })
        } else {
            this.editId = -1;
            this.applyForm.reset();
        }
    }
    handleCancel() {
        this.isShow = false;
    }
    onDateChange(date) {
        this.rangeDate[0] = this.datePipe.transform(date[0], 'yyyy-MM-dd') + " 00:00:00";
        this.rangeDate[1] = this.datePipe.transform(date[1], 'yyyy-MM-dd') + " 23:59:59";
        if(!date[0]){
            this.rangeDate = []
        }
        this.pageIndex = 1;
        this.getList();
    }
    onSearchHouseChange() {
        this.pageIndex = 1;
        this.getList();
    }
    onSourceAreaChange(areaId) {
        if (!areaId) return;
        this.applyForm.patchValue({
            batch:'',
            batchNum:''
        })
        let _controls = this.applyForm.controls;
        if (_controls.targetArea.value) {
            _controls.targetArea.markAsDirty();
            _controls.targetArea.updateValueAndValidity();
        }
        this.getBatch(areaId);
    }
    clickPage(pageIndex){
        this.pageIndex = pageIndex;
        this.getList();
    }
    onTargetAreaChange() {
        let _controls = this.applyForm.controls;
        if (_controls.sourceArea.value) {
            _controls.sourceArea.markAsDirty();
            _controls.sourceArea.updateValueAndValidity();
        }
    }
    onMaterialChange(code) {
        this.applyForm.patchValue({
            sourceHouse: '',
            sourceArea: '',
            targetHouse: '',
            targetArea: '',
            batch:'',
            batchNum:''
        })
        if (!code) return;
        this.selectedMaterialItem = this.filterName(this.subMaterialList, code)
        this.applyForm.controls["materialName"].setValue(this.selectedMaterialItem.name);
        this.getMateriHouse(this.selectedMaterialItem.id);
    }
    filterName(arr, id) {
        let _item: any = null;
        if (arr.length > 0) {
            for (let i = 0; i < arr.length; i++) {
                if (arr[i].id === id || arr[i].code === id || arr[i].warehouseAreaId === id || arr[i].value === id) {
                    _item = arr[i];
                    return _item;
                } else {
                    if (arr[i].children) {
                        this.filterName(arr[i].children, id)
                    }
                }
            }
        }
    }
    onSourceHouseChange(id, type) {
        if (!id) return;
        let _controls = this.applyForm.controls;
        if (type == 1) {
            this.sourceHouseId = id;
            this.applyForm.patchValue({
                sourceArea:'',
                batch:'',
                batchNum:''
            })
            this.getMateriArea(1);
            if (_controls.targetHouse.value) {
                _controls.targetHouse.markAsDirty();
                _controls.targetHouse.updateValueAndValidity();
            }
        }
        if (type == 2) {
            this.targetHouseId = id;
            this.applyForm.patchValue({
                targetArea:''
            })
            this.getMateriArea(2);
            if (_controls.sourceHouse.value) {
                _controls.sourceHouse.markAsDirty();
                _controls.sourceHouse.updateValueAndValidity();
            }
        }
    }
    onBatchChange(code) {
        if (!code || !this.batchData.length) return;
        let _data = this.batchData.filter(item => {
            return item.barcodeBatch === code
        })[0];
        this.applyForm.controls["batchNum"].setValue(_data.weight)
    }
    onChooseTypeChange(type) {
        if (!this.batchData.length) return;
        this.chooseTypeValue = type
        if (type == 1) {            // 系统
            this.applyForm.controls.batch.setValue(this.batchData[0].barcodeBatch)
        }
    }
    onMoveTypeChange(id) {
        if (!id) return;
        this.applyForm.controls.sourceHouse.markAsDirty();
        this.applyForm.controls.sourceHouse.updateValueAndValidity();
        this.applyForm.controls.targetHouse.markAsDirty();
        this.applyForm.controls.targetHouse.updateValueAndValidity();
    }
    getMateriHouse(id) {
        this.applyService.apiHouseByMateriId(id).subscribe(res => {
            this.materiHouseData = res;
        })
    }
    getMateriArea(type) {
        let _dataJson = {
            materialId: this.selectedMaterialItem.id,
            warehouseId: type == 1 ? this.sourceHouseId : this.targetHouseId
        }
        this.applyService.apiAreaByMateriId(_dataJson).subscribe(res => {
            if (type == 1) {
                this.sourceAreaData = res;
            }
            if (type == 2) {
                this.targetAreaData = res;
            }
        })
    }
    getBatch(areaId) {
        let _dataJson = {
            materialId: this.selectedMaterialItem.id,
            warehouseId: this.sourceHouseId,
            warehouseAreaId: areaId
        }
        this.applyService.apiBatchByMateriId(_dataJson).subscribe(res => {
            this.batchData = res;
        })
    }
    getList() {
        let _newData = {}
        let _dataJson = {
            fromStorehouse: this.sourceWareHouseSearch,
            page: this.pageIndex,
            size: this.pagesize,
            sort: 'createDate,desc'
        }
        console.log(this.rangeDate[0])
        if(this.rangeDate[0]){
            _newData = {
                ..._dataJson,
                createDate: this.rangeDate
            }
        }else{
            _newData = {
                ..._dataJson
            }
        }
        this.applyService.apiList(_newData).subscribe(res => {
            this.listData = res.content;
            this.dataCount = res.totalElements
        })
    }
    getSourceHouseList() {
        this.applyService.apiSourceHouse().subscribe(res => {
            this.sourceHouseData = res;
        })
    }
    getSubMaterialList() {
        this.applyService.apiSubMaterial().subscribe(res => {
            this.subMaterialList = res;
        })
    }
    getMoveWareType() {
        this.applyService.apiChooseTypeList("movement_type").subscribe(res => {
            this.moveWareTypeList = res;
        });
    }
    getChooseWareType() {
        this.applyService.apiChooseTypeList("picking_type").subscribe(res => {
            this.chooseWareTypeList = res;
        })
    }

    del(data) {
        this.modal.confirm({
            nzTitle: "提示",
            nzContent: "确定删除数据？",
            nzOnOk: () => {
                let _dataJson = {
                    id: data.id
                }
                this.applyService.apidel(_dataJson).subscribe(res => {
                    this.nzmessage.success("删除成功");
                    this.pageIndex = 1;
                    this.getList();
                })
            }
        })
    }
    editStatus(data, status: number) {
        this.modal.confirm({
            nzTitle: "提示",
            nzContent: "确定提交数据？",
            nzOnOk: () => {
                let _dataJson = {
                    id: data.id,
                    status: status
                }
                this.applyService.apiEditStatus(_dataJson).subscribe(res => {
                    this.nzmessage.success("提交成功");
                    this.pageIndex = 1;
                    this.getList();
                })
            }
        })
    }
    modalAdd(e) {
        if (e) {
            e.preventDefault();
        }
        for (const i in this.applyForm.controls) {
            this.applyForm.controls[i].markAsDirty();
            this.applyForm.controls[i].updateValueAndValidity();
        }
        if (this.applyForm.status === "VALID") {
            let _value = this.applyForm.value;
            _value.id = this.modalList.length === 0 ? 1 : (this.modalList[this.modalList.length - 1].id + 1)
            let _sourceHouseItem = this.filterName(this.materiHouseData, _value.sourceHouse);
            let _sourceAreaItem = this.filterName(this.sourceAreaData, _value.sourceArea);
            let _targetHouseItem = this.filterName(this.materiHouseData, _value.targetHouse);
            let _targetAreaItem = this.filterName(this.targetAreaData, _value.targetArea);
            let _chooseItem = this.filterName(this.chooseWareTypeList, _value.chooseType);
            /* let _batchItem = this.filterName(this.batchData, _value.batch); */
            _value.sourceHouseName = _sourceHouseItem.name;
            _value.sourceAreaName = _sourceAreaItem.warehouseAreaName;
            _value.targetHouseName = _targetHouseItem.name;
            _value.targetAreaName = _targetAreaItem.warehouseAreaName;
            _value.chooseName = _chooseItem.label;
            /* _value.batchName = _batchItem.barcodeBatch; */
            _value.materialId = this.selectedMaterialItem.id;
            this.modalList = [...this.modalList, _value];
            this.applyForm.reset();
        }
    }
    modalDel() {
        let _arr = []
        for (let i = 0; i < this.modalList.length; i++) {
            let _item = this.modalList[i]
            if (this.deleteIds.indexOf(_item.id) === -1) {
                _arr.push(_item)
            }
        }
        this.modalList = [..._arr];
        this.deleteIds = [];
        this.checkedArr = {};
        this.isAllChecked = false;
        this.isHalfChecked = this.modalList.some(item => {
            return this.checkedArr[item.id] && !this.isAllChecked
        })
    }
    checkAll(status: boolean) {
        this.modalList.map(item => {
            this.checkedArr[item.id] = status
        })
        this.isHalfChecked = false;
        this.filterDelData();
    }
    checkItem() {
        this.isAllChecked = this.modalList.every(item => {
            return this.checkedArr[item.id]
        })
        this.isHalfChecked = this.modalList.some(item => {
            return this.checkedArr[item.id] && !this.isAllChecked
        })
        this.filterDelData();
    }
    filterDelData() {
        this.deleteIds = [];
        for (const key in this.checkedArr) {
            if (this.checkedArr[key]) {
                this.deleteIds.push(Number(key));
            }
        }
    }

    submitFn() {
        let _dataJson = [];
        let _modalCheckList = [];
        if( this.editId === -1 ){
            this.modalList.forEach(item => {
                if (this.deleteIds.indexOf(item.id) > -1) {
                    _modalCheckList.push(item)
                }
            })
        }else{
            _modalCheckList = [this.applyForm.value]
        }
        
        for (let i = 0; i < _modalCheckList.length; i++) {
            let _item = _modalCheckList[i];
            _dataJson.push({
                barcodeBatch: _item.batch,
                fromStorehouse: {
                    id: _item.sourceHouse
                },
                fromStorehouseArea: {
                    id: _item.sourceArea
                },
                materialCode: _item.materialCode,
                materialId: _item.materialId,
                materialName: _item.materialName,
                pickingType: _item.chooseType,
                movementType: _item.moveType,
                reqAmount: _item.moveNum,
                status: 0,
                toStorehouse: {
                    id: _item.targetHouse
                },
                toStorehouseArea: {
                    id: _item.targetArea
                }
            })
        }
        if (_dataJson.length === 0) {
            this.nzmessage.warning("请选择要提交的数据")
            return false;
        }
        if (this.editId === -1) {
            this.applyService.apiAdd(_dataJson).subscribe(res => {
                this.isShow = false;
                this.getList();
                this.modalList = [];
            })
        } else {
            if(_dataJson[0].barcodeBatch==''){
                this.nzmessage.create('error','请选择批次')
            }else{
                let _data = {
                    ..._dataJson[0],
                    id: this.editId
                }
                this.applyService.apiEdit(_data).subscribe(res => {
                    console.log(res);
                    this.isShow = false;
                    this.getList();
                    this.modalList = [];
                })
            }
        }
    }
}
